<template>
	<view class="order-list-container page-container">
		<!-- 订单状态筛选 -->
		<view class="status-tabs">
			<view class="tab-item" v-for="(tab, index) in statusTabs" :key="index"
				:class="{ active: activeTab === index }" @click="switchTab(index)">
				<text class="tab-text">{{ tab.name }}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">

			<view class="order-card" v-for="(order, index) in displayOrderList" :key="order.id"
				@click="toOrderDetail(order)">
				<!-- 订单头部 -->
				<view class="order-header">
					<view class="order-info">
						<text class="order-number">订单号：{{ order.order_no }}</text>
						<text class="order-date">{{ order.create_time }}</text>
					</view>
					<view class="order-status" :class="'status-' + getStatusText(order.order_status)">
						{{ order.order_status_desc }}
					</view>
				</view>

				<!-- 商品列表 -->
				<view class="product-list">
					<view class="product-item" v-for="(product, pIndex) in order.products" :key="pIndex">
						<image :src="$tools.buildUrl(product.main_image)" mode="aspectFill" class="product-image">
						</image>
						<view class="product-info">
							<text class="product-name">{{ product.spu_name }}</text>
							<text class="product-spec">{{ product.sku_name }}</text>
							<view class="product-bottom">
								<text class="product-price">¥{{ product.actual_price }}</text>
								<text class="product-quantity">x{{ product.quantity }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 订单总计 -->
				<view class="order-summary">
					<text class="summary-text">共{{ order.item_count }}件商品</text>
					<text class="summary-amount">实付款：¥{{ order.pay_amount }}</text>
				</view>

				<!-- 订单操作 -->
				<!-- 订单状态：0-待确认/待支付  2-已支付 3-备货中 4-部分发货 5-已发货（全部发货）6-已取消 7-已完成（已收货） -->
				<view class="order-actions">
					<button class="action-btn cancel-btn" v-if="order.order_status === 0"
						@click.stop="cancelOrder(order)">
						取消订单
					</button>
					<button class="action-btn pay-btn" v-if="order.order_status === 0" @click.stop="payOrder(order)">
						立即付款
					</button>
					<button class="action-btn confirm-btn" v-if="order.order_status === 4 || order.order_status === 5"
						@click.stop="confirmReceive(order)">
						确认收货
					</button>
					<button class="action-btn review-btn" v-if="order.order_status === 7 && !(order.comment_count>0)"
						@click.stop="evaluateOrder(order)">
						商品评价
					</button>
					<button class="action-btn after-sale-btn"
						v-if="order.order_status === 2 || order.order_status === 7" @click.stop="applyAfterSale(order)">
						申请售后
					</button>
					<button class="action-btn detail-btn" @click.stop="toOrderDetail(order)">
						查看详情
					</button>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="displayOrderList.length === 0">
			<image src="@/static/images/cart-green.png" mode="aspectFit" class="empty-image">
			</image>
			<text class="empty-text">暂无相关订单</text>
			<text class="empty-desc">快去商城选购您喜欢的茶叶吧</text>
			<button class="go-shopping-btn" @click="goShopping">去购物</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				activeTab: 0,
				statusTabs: [{
						name: '全部',
						status: 0
					},
					{
						name: '待付款',
						status: 1
					},
					{
						name: '待发货',
						status: 2
					},
					{
						name: '待收货',
						status: 3
					},
					{
						name: '已完成',
						status: 4
					},
					{
						name: '已取消',
						status: 5
					}
				],
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				// 显示的订单列表
				displayOrderList: []
			}
		},
		onLoad(options) {
			// 如果有传入状态参数，自动切换到对应tab
			if (options.status) {
				const index = this.statusTabs.findIndex(tab => tab.status === Number(options.status))
				if (index >= 0) {
					this.activeTab = index
				}
			}
			this.onSearch();
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.displayOrderList = []
				this.filterOrderList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.filterOrderList()
				}, 500)
			}
		},
		methods: {
			// 切换tab
			switchTab(index) {
				this.activeTab = index
				this.onSearch()
			},
			// 筛选订单列表
			filterOrderList() {
				if (this.hasSearched) {
					return false
				}

				this.hasSearched = true
				const currentStatus = this.activeTab >= 0 ? this.statusTabs[this.activeTab].status : 0;
				this.$api.order.GetOrdersList({
					page: this.page,
					limit: this.limit,
					status: currentStatus
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					this.displayOrderList = this.displayOrderList.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},
			// 搜索事件处理
			onSearch(searchQuery) {
				this.page = 1
				this.recordCount = 0
				this.displayOrderList = []
				this.filterOrderList()
			},
			// 获取状态标识
			getStatusText(status) {
				// 订单状态：0-待确认/待支付（订单创建完毕）2-已支付 3-备货中 4-部分发货 5-已发货（全部发货）6-已取消 7-已完成（已收货）
				const statusMap = {
					0: 'pending',
					2: 'paid',
					5: 'shipped',
					7: 'completed',
					6: 'cancelled'
				}
				return statusMap[status] || 'default'
			},

			// 跳转到订单详情
			toOrderDetail(order) {
				uni.navigateTo({
					url: `/pages/order/detail?orderId=${order.id}`
				})
			},
			// 取消订单
			cancelOrder(order) {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消这个订单吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.order.CancelOrders({
								id: order.id
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								order.order_status = 6
								order.order_status_desc = '已取消'
							})
						}
					}
				})
			},
			// 支付订单
			payOrder(order) {
				uni.navigateTo({
					url: `/pages/order/payment?order_ids=${order.id}&type=pay`
				})
			},
			// 确认收货
			confirmReceive(order) {
				uni.showModal({
					title: '确认收货',
					content: '确认已收到商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.order.ReceiverOrders({
								id: order.id
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								order.order_status = 7
								order.order_status_desc = '已完成'
							})
						}
					}
				})
			},
			// 评价订单
			evaluateOrder(order) {
				uni.navigateTo({
					url: `/pages/order/evaluate?orderId=${order.id}`
				})
			},
			// 申请售后
			applyAfterSale(order) {
				uni.navigateTo({
					url: `/pages/after-sale/apply?orderId=${order.id}`
				})
			},
			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 更新打单状态
			setOrderStatus(orderid, status, desc) {
				let item = this.displayOrderList.find(item => item.id === orderid)
				if (item) {
					item.order_status = status
					item.order_status_desc = desc
				}
			},
			// 更新评价状态
			setComment(orderid) {
				let item = this.displayOrderList.find(item => item.id === orderid)
				if (item) {
					item.comment_count++
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-list-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	.status-tabs {
		background-color: #ffffff;
		display: flex;
		padding: 0 20rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 30rpx 10rpx;
		position: relative;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #52a58a;
	}

	.tab-text {
		font-size: 26rpx;
		color: #666;
		white-space: nowrap;
	}

	.tab-item.active .tab-text {
		color: #52a58a;
		font-weight: 600;
	}

	.order-list {
		padding: 20rpx;
	}

	.order-card {
		background-color: #ffffff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 30rpx 20rpx;
		background-color: #f8f9fa;
		border-bottom: 1rpx solid #eee;
	}

	.order-info {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.order-number {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.order-date {
		font-size: 24rpx;
		color: #666;
	}

	.order-status {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.status-pending {
		background-color: #fff3cd;
		color: #856404;
	}

	.status-paid {
		background-color: #d1ecf1;
		color: #0c5460;
	}

	.status-shipped {
		background-color: #fff3cd;
		color: #856404;
	}

	.status-completed {
		background-color: #d4edda;
		color: #155724;
	}

	.status-cancelled {
		background-color: #f8d7da;
		color: #721c24;
	}

	.product-list {
		padding: 20rpx 30rpx;
	}

	.product-item {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.product-item:last-child {
		margin-bottom: 0;
	}

	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
	}

	.product-info {
		flex: 1;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
		line-height: 1.4;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 12rpx;
		display: block;
	}

	.product-bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-price {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff4757;
	}

	.product-quantity {
		font-size: 24rpx;
		color: #666;
	}

	.order-summary {
		padding: 20rpx 30rpx;
		background-color: #f8f9fa;
		border-top: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.summary-text {
		font-size: 26rpx;
		color: #666;
	}

	.summary-amount {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.order-actions {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
		border-top: 1rpx solid #eee;
	}

	.action-btn {
		border: none;
		border-radius: 20rpx;
		padding: 0 24rpx;
		font-size: 24rpx;
		font-weight: 500;
		min-width: 120rpx;
		text-align: center;
	}

	.cancel-btn {
		background-color: transparent;
		color: #666;
		border: 1rpx solid #ddd;
	}

	.pay-btn {
		background-color: #52a58a;
		color: #ffffff;
	}

	.confirm-btn {
		background-color: #52a58a;
		color: #ffffff;
	}

	.review-btn {
		background-color: transparent;
		color: #52a58a;
		border: 1rpx solid #52a58a;
	}

	.after-sale-btn {
		background-color: transparent;
		color: #ff6b35;
		border: 1rpx solid #ff6b35;
	}

	.detail-btn {
		background-color: transparent;
		color: #666;
		border: 1rpx solid #ddd;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 40rpx;
		text-align: center;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}

	.empty-text {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 60rpx;
		line-height: 1.4;
	}

	.go-shopping-btn {
		background-color: #52a58a;
		color: #ffffff;
		border: none;
		border-radius: 40rpx;
		padding: 0rpx 60rpx;
		font-size: 28rpx;
		font-weight: 500;
	}
</style>